import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class saleCake {
    public static void main(String[] args) {

        Cake cake = new Cake();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) cake.make();
        }, "a").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) cake.make();
        }, "b").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) cake.buy();
        }, "c").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) cake.buy();
        }, "d").start();

    }
}

class Cake {

    private int num;
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    public void make() {
        lock.lock();
        try {
            while (num == 1) condition.await();
            num++;
            System.out.println(Thread.currentThread().getName() + "制作" + num);
            condition.signalAll();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    public void buy() {
        //加锁
        lock.lock();
        try {
            //判断
            //循环判断，下飞机了，安检后上飞机
            //if虚假唤醒
            while (num != 1) condition.await();
            //干活
            num--;
            System.out.println(Thread.currentThread().getName() + "买" + num);
            //通知
            condition.signalAll();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //解锁
            lock.unlock();
        }
    }

}
